package com.hghivln.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hghivln.constants.Constants;
import com.hghivln.mapper.*;
import com.hghivln.pojo.domain.*;
import com.hghivln.pojo.dto.PatientDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.pojo.vo.PatientVo;
import com.hghivln.service.PatientService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service
public class PatientServiceImpl implements PatientService {

    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private PatientFileMapper patientFileMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private CareOrderMapper careOrderMapper;

    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Override
    public AjaxResult listPatientForPage(PatientDto patientDto) {
        Page<Patient> page = new Page<>(patientDto.getPageNum(), patientDto.getPageSize());
        QueryWrapper<Patient> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(patientDto.getName()), Patient.COL_NAME, patientDto.getName());
        qw.like(StringUtils.isNotBlank(patientDto.getPhone()), Patient.COL_PHONE, patientDto.getPhone());
        qw.like(StringUtils.isNotBlank(patientDto.getIdCard()), Patient.COL_ID_CARD, patientDto.getIdCard());
        patientMapper.selectPage(page, qw);
        List<PatientVo> list = new ArrayList<>();
        for (Patient patient : page.getRecords()) {
            PatientVo patientVo = new PatientVo();
            BeanUtils.copyProperties(patient,patientVo);
            list.add(patientVo);
        }
        return AjaxResult.success("操作成功",list,page.getTotal());
    }

    @Override
    public AjaxResult selectPatientById(String patientId) {
        Patient patient = patientMapper.selectById(patientId);
        PatientVo patientVo = new PatientVo();
        BeanUtils.copyProperties(patient,patientVo);
        return AjaxResult.success(patientVo);
    }

    @Override
    public AjaxResult selectPatientFileById(String patientId) {
        List<CareHistory> careHistoryList = careHistoryMapper.selectCareHistoryById(patientId);
        List<Map<String,Object>> list = new ArrayList<>();
        for (CareHistory careHistory : careHistoryList) {
            Map<String, Object> careHistoryMap = BeanUtil.beanToMap(careHistory);
            careHistoryMap.put("careOrders", Collections.EMPTY_LIST);

            List<Map<String,Object>> listCareOrders = new ArrayList<>();
            // 跟据病例Id查询处方列表
            QueryWrapper<CareOrder> qw=new QueryWrapper<>();
            qw.eq(CareOrder.COL_CH_ID,careHistory.getChId());
            List<CareOrder> careOrders = careOrderMapper.selectList(qw);

            for (CareOrder careOrder : careOrders) {
                Map<String, Object> careOrderMap = BeanUtil.beanToMap(careOrder);
                // 根据处方Id查询处方详情
                QueryWrapper<CareOrderItem> qwI=new QueryWrapper<>();
                qw.eq(CareOrder.COL_CO_ID,careOrder.getCoId());
                List<CareOrderItem> careOrderItems = careOrderItemMapper.selectList(qwI);
                careOrderMap.put("careOrderItems",careOrderItems);
                listCareOrders.add(careOrderMap);
            }
            careHistoryMap.put("careOrders",listCareOrders);
            list.add(careHistoryMap);
        }
        return AjaxResult.success(list);

    }

    @Override
    public AjaxResult selectPatientAllMessageByPatientId(String patientId) {
        return AjaxResult.success(patientMapper.selectPatientAllMessageByPatientId(patientId));
    }

    @Override
    public AjaxResult selectPatientByIdCard(String idCard) {
        Patient patient = patientMapper.selectPatientByIdCard(idCard);
        if (ObjectUtils.isEmpty(patient)) {
            return AjaxResult.fail("【" + idCard + "】对应的患者信息不存在，请在下面新建患者信息");
        } else {
            return AjaxResult.success(patient);
        }
    }

    /**
     * 跟据挂号单号查询挂号信息
     * 更爱挂号单状态
     */
    @Override
    public AjaxResult receivePatient(String regId, User user) {
        synchronized (this) { //防止并发接诊的问题
            QueryWrapper<Registration> qw = new QueryWrapper<>();
            qw.eq(Registration.COL_REG_ID,regId);
            Registration registration = registrationMapper.selectOne(qw);
            if (ObjectUtils.isNotEmpty(registration)) {
                if (!registration.getRegStatus().equals(Constants.REG_STATUS_2)) {
                    registration.setRegStatus(Constants.REG_STATUS_2);
                    registration.setDoctorName(user.getUserName());
                    registration.setUserId(user.getUserId());
                    return AjaxResult.toAjax(registrationMapper.updateById(registration));
                }else {
                    return AjaxResult.fail("【"+regId+"】挂号单的状态不是待就诊状态，不能接诊");
                }
            } else {
                return AjaxResult.fail("【"+regId+"】挂号单的不存在，不能接诊");
            }
         }
    }


    @Override
    public AjaxResult getPatientAllMessageByPatientId(String patientId) {
        Patient patient = patientMapper.selectById(patientId);
        PatientVo patientVo = new PatientVo();
        BeanUtils.copyProperties(patient,patientVo);
        PatientFile patientFile = patientFileMapper.selectPatientFileById(patientId);
        List<CareHistory> careHistoryList = careHistoryMapper.selectCareHistoryById(patientId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("patient",patient);
        map.put("patientFile",patientFile);
        map.put("careHistoryList",careHistoryList);
        return AjaxResult.success(map);
    }

}
